using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using QFramework;
using QGameFramework;

public class TCPServer : BaseComponent
{
    private Socket server;
    private static Dictionary<Socket, ClientState> clients = new Dictionary<Socket, ClientState>();
    private string str;
    public void StartServer(int gameConfigPort)
    {
        server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
        IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, gameConfigPort);
        server.Bind(ipEndPoint);
        server.Listen(0);
        LogKit.I("[服务器]启动成功！");
        server.BeginAccept(AcceptCallBack, server);
    }

    public void Send(string msg)
    {
        byte[] sendBytes = System.Text.Encoding.Default.GetBytes(msg);
        server.Send(sendBytes);
    }

    private void AcceptCallBack(IAsyncResult ar)
    {
        try
        {
            Console.WriteLine("[服务器]Accept");
            Socket listenfd = (Socket)ar.AsyncState;
            Socket clientfd = listenfd.EndAccept(ar);
            //clients列表
            ClientState state = new ClientState();
            state.socket = clientfd;
            clients.Add(clientfd, state);
            //接收数据BeginReceive
            clientfd.BeginReceive(state.readBuff, 0, 1024, 0, ReceiveCallback, state);
            //继续Accept
            listenfd.BeginAccept(AcceptCallBack, listenfd);
        }
        catch (SocketException ex)
        {
            Console.WriteLine("Socket Accept fail" + ex.ToString());
        }
    }


    private void ReceiveCallback(IAsyncResult ar)
    {
        try
        {
            ClientState state = (ClientState)ar.AsyncState;
            Socket clientfd = state.socket;
            int count = clientfd.EndReceive(ar);
            //客户端关闭
            if (count == 0)
            {
                clientfd.Close();
                clients.Remove(clientfd);
                Console.WriteLine("Socket Close");
                return;
            }

            string recvStr = System.Text.Encoding.Default.GetString(state.readBuff, 0, count);
            str = recvStr;
            LogKit.I($"接收到客户端的消息：{recvStr}");
            byte[] sendBytes = System.Text.Encoding.Default.GetBytes("echo" + recvStr);
            clientfd.Send(sendBytes); //减少代码量，不用异步
            clientfd.BeginReceive(state.readBuff, 0, 1024, 0, ReceiveCallback, state);
        }
        catch (SocketException ex)
        {
            Console.WriteLine("Socket Receive fail" + ex.ToString());
        }
    }
    private void Update()
    {
        if (str != null)
        {
            // this.SendEvent<>();
            str = null;
        }
    }
}

class ClientState
{
    public Socket socket;
    public byte[] readBuff = new byte[1024];
}